package com.idlecode.util;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.VirtualFile;

import java.io.File;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-03-26 09:54
 **/
public class VcsUtil {

    /**
     * 判断当前项目使用vcs(项目管理工具)
     *
     * @param project
     * @return
     */
    public static String detectVcs(Project project) {
        String projectBasePath = project.getBasePath();
        File svnFolder = new File(projectBasePath + "/.svn");
        File gitFolder = new File(projectBasePath + "/.git");

        if (svnFolder.exists()) {
            return "SVN";
        } else if (gitFolder.exists()) {
            return "Git";
        } else {
            return "Unknown";
        }
    }

    /**
     * 刷新vsc
     *
     * @param project
     */
    public static void refreshVcs(Project project) {
        ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
        String vcsType = detectVcs(project);
        AbstractVcs vcs = null;
        if ("SVN".equals(vcsType)) {
            vcs = vcsManager.findVcsByName("svn");
        } else if ("Git".equals(vcsType)) {
            vcs = vcsManager.findVcsByName("Git");
        }
        if (vcs != null) {
            VirtualFile[] vcsRoots = vcsManager.getRootsUnderVcs(vcs);
            for (VirtualFile vcsRoot : vcsRoots) {
                vcsRoot.refresh(false, true);
            }
        }
    }
}
